package com.example.common.utils;

import com.example.common.constanst.RedisConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: TODO
 * @author: uu
 * @date: 2024/2/29 1:46
 * @version: 1.0
 */
@Component
public class JwtUtil {
    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    public void setSecret(String secret) {
        this.secret = secret;
    }
    /**
     * @description: 创建token
     * @author: uu
     * @date: 2024/2/29 2:07
     * @version: 1.0
     */
    public String createToken(Map<String, Object> map) {
//        log.info("secret = {}", secret);
        String token = Jwts.builder()
                .setClaims(map)
                .setIssuedAt(Calendar.getInstance().getTime())
                .setExpiration(new Date(System.currentTimeMillis() + 30 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS256, secret)
//                .signWith(SignatureAlgorithm.ES256, secret)
                .compact();
        return token;
    }

    /**
     * @description: 解析token
     * @author: uu
     * @date: 2024/2/29 2:07
     * @version: 1.0
     */
    public Claims parseToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }

    /**
     * @description: 根据token值查询redis中的用户信息
     * @author: uu
     * @date: 2024/3/1 1:15
     * @version: 1.0
     */
    public Object getLoginUser(String uuid) {
        return redisCacheUtil.getCacheObject(RedisConstant.LOGIN_USER_KEY + uuid);
    }
    /**
     * @description: 根据uuid删除redis中的用户信息
     * @author: uu
     * @date: 2024/3/8 21:40
     * @version: 1.0
     */
    public Object removeLoginUser(String uuid) {
        return redisCacheUtil.deleteObject(RedisConstant.LOGIN_USER_KEY + uuid);
    }

    /**
     * @description: 刷新token
     * @author: uu
     * @date: 2024/3/1 1:36
     * @version: 1.0
     */
    public void refreshToken(Object loginUserVO, String token) {
        Claims claims = parseToken(token);
        String uuid = (String) claims.get("token");
        redisCacheUtil.setCacheObject(RedisConstant.LOGIN_USER_KEY + uuid, loginUserVO, 30, TimeUnit.MINUTES);
    }
}
